#include "ModbusController.h"
#include "utils/Logger.h"
#include <QDebug>

ModbusController::ModbusController(QObject *parent)
    : QObject(parent),
      m_deviceModel(nullptr),
      m_dataRecordModel(nullptr),
      m_isConnected(false),
      m_connectionStatus("未连接")
{
}

ModbusController::~ModbusController()
{
    // 断开所有设备
    disconnectAllDevices();

    // 清理所有资源
    qDeleteAll(m_modbusServices);
    qDeleteAll(m_dataCollectors);
}

// 设置设备模型
void ModbusController::setDeviceModel(DeviceModel *model)
{
    m_deviceModel = model;
    qDebug() << "ModbusController: 设置 DeviceModel";
}

// 设置实时数据模型
void ModbusController::setDataRecordModel(DataRecordModel *model)
{
    m_dataRecordModel = model;
    qDebug() << "ModbusController: 设置 DataRecordModel";
}

// 连接到设备
bool ModbusController::connectToDevice(const QString &deviceId)
{
    qInfo() << "ModbusController: 连接设备 -" << deviceId;

    // 检查设备模型
    if (!m_deviceModel)
    {
        qWarning() << "ModbusController: DeviceModel 未设置";
        return false;
    }

    // 获取设备信息
    Device device = m_deviceModel->getDeviceById(deviceId);
    if (!device.isValid())
    {
        qWarning() << "ModbusController: 设备不存在:" << deviceId;
        emit deviceConnectionFailed(deviceId, "设备不存在");
        return false;
    }

    // 检查是否已连接
    if (isDeviceConnected(deviceId))
    {
        qInfo() << "ModbusController: 设备已连接:" << deviceId;
        switchToDevice(deviceId);
        return true;
    }

    // 创建 ModbusService
    ModbusService *modbusService = createModbusService(deviceId);
    if (!modbusService)
    {
        qWarning() << "ModbusController: 创建 ModbusService 失败";
        return false;
    }

    // 连接到设备
    if (!modbusService->connectToDevice(device))
    {
        qWarning() << "ModbusController: 连接失败:" << modbusService->lastError();
        emit deviceConnectionFailed(deviceId, modbusService->lastError());
        cleanupDevice(deviceId);
        return false;
    }

    // 更新设备状态为连接中
    m_deviceModel->updateDeviceStatus(deviceId, "connecting");

    // 切换当前设备并提示连接中
    switchToDevice(deviceId);
    updateConnectionStatus(QString("连接中: %1").arg(deviceId));

    qInfo() << "ModbusController: 已发起连接请求 -" << deviceId;

    return true;
}

// 断开设备连接
void ModbusController::disconnectFromDevice(const QString &deviceId)
{
    qInfo() << "ModbusController: 断开设备 -" << deviceId;

    // 停止数据采集
    stopDataCollection(deviceId);

    // 获取 ModbusService
    ModbusService *modbusService = getModbusService(deviceId);
    if (modbusService)
    {
        modbusService->disconnectFromDevice();
    }

    // 更新设备状态
    if (m_deviceModel)
    {
        m_deviceModel->updateDeviceStatus(deviceId, "offline");
    }

    // 清理资源
    cleanupDevice(deviceId);

    // 如果是当前设备，清空状态
    if (m_currentDeviceId == deviceId)
    {
        m_currentDeviceId.clear();
        m_isConnected = false;
        updateConnectionStatus("未连接");
        emit currentDeviceIdChanged();
        emit isConnectedChanged();
    }

    emit deviceDisconnected(deviceId);
}

// 断开当前设备
void ModbusController::disconnectCurrentDevice()
{
    if (!m_currentDeviceId.isEmpty())
    {
        disconnectFromDevice(m_currentDeviceId);
    }
}

// 断开所有设备
void ModbusController::disconnectAllDevices()
{
    qInfo() << "ModbusController: 断开所有设备";

    QStringList deviceIds = m_modbusServices.keys();
    for (const QString &deviceId : deviceIds)
    {
        disconnectFromDevice(deviceId);
    }
}

// 启动数据采集
bool ModbusController::startDataCollection(const QString &deviceId, int intervalMs)
{
    qInfo() << "ModbusController: 启动数据采集 -" << deviceId << "间隔:" << intervalMs << "ms";

    // 检查设备是否已连接
    if (!isDeviceConnected(deviceId))
    {
        qWarning() << "ModbusController: 设备未连接:" << deviceId;
        emit dataCollectionFailed(deviceId, "设备未连接");
        return false;
    }

    // 获取或创建 DataCollector
    DataCollector *collector = getDataCollector(deviceId);
    if (!collector)
    {
        collector = createDataCollector(deviceId);
        if (!collector)
        {
            qWarning() << "ModbusController: 创建 DataCollector 失败";
            return false;
        }
    }

    ModbusService *modbusService = getModbusService(deviceId);
    if (!modbusService)
    {
        qWarning() << "ModbusController: 未找到 ModbusService" << deviceId;
        emit dataCollectionFailed(deviceId, "Modbus 服务未就绪");
        return false;
    }

    // 检查是否已在采集
    if (collector->isCollecting())
    {
        qInfo() << "ModbusController: 数据采集已在运行:" << deviceId;
        return true;
    }

    // 设置设备和采集周期
    Device device = m_deviceModel->getDeviceById(deviceId);
    collector->setDevice(device);
    collector->setCollectionInterval(intervalMs);
    collector->setModbusService(modbusService);

    // 启动采集
    collector->startCollection();

    // 记录日志
    Logger::instance()->logOperation("start_collection", deviceId,
                                     QString("启动数据采集，间隔 %1ms").arg(intervalMs));

    qInfo() << "ModbusController: 数据采集已启动 -" << deviceId;
    emit dataCollectionStarted(deviceId);

    return true;
}

// 停止数据采集
void ModbusController::stopDataCollection(const QString &deviceId)
{
    qInfo() << "ModbusController: 停止数据采集 -" << deviceId;

    DataCollector *collector = getDataCollector(deviceId);
    if (collector && collector->isCollecting())
    {
        collector->stopCollection();

        // 记录日志
        Logger::instance()->logOperation("stop_collection", deviceId, "停止数据采集");

        emit dataCollectionStopped(deviceId);
    }
}

// 读取单次数据
bool ModbusController::readDeviceData(const QString &deviceId)
{
    qInfo() << "ModbusController: 读取设备数据 -" << deviceId;

    ModbusService *modbusService = getModbusService(deviceId);
    if (!modbusService || !modbusService->isConnected())
    {
        qWarning() << "ModbusController: 设备未连接:" << deviceId;
        return false;
    }

    // 读取输入寄存器（地址 0，共 6 个寄存器：温度、压力、流量各占 2 个）
    return modbusService->readInputRegisters(0, 6);
}

// 检查设备是否已连接
bool ModbusController::isDeviceConnected(const QString &deviceId) const
{
    ModbusService *modbusService = getModbusService(deviceId);
    return modbusService && modbusService->isConnected();
}

// 检查设备是否正在采集
bool ModbusController::isDeviceCollecting(const QString &deviceId) const
{
    DataCollector *collector = getDataCollector(deviceId);
    return collector && collector->isCollecting();
}

// 获取已连接设备列表
QStringList ModbusController::getConnectedDevices() const
{
    QStringList connectedDevices;
    for (auto it = m_modbusServices.constBegin(); it != m_modbusServices.constEnd(); ++it)
    {
        if (it.value()->isConnected())
        {
            connectedDevices.append(it.key());
        }
    }
    return connectedDevices;
}

// 切换当前设备
void ModbusController::switchToDevice(const QString &deviceId)
{
    if (m_currentDeviceId == deviceId)
        return;

    m_currentDeviceId = deviceId;
    m_isConnected = isDeviceConnected(deviceId);

    if (m_isConnected)
    {
        updateConnectionStatus(QString("已连接: %1").arg(deviceId));
    }
    else
    {
        updateConnectionStatus("未连接");
    }

    emit currentDeviceIdChanged();
    emit isConnectedChanged();

    qDebug() << "ModbusController: 切换到设备 -" << deviceId;
}

// ModbusService 连接成功
void ModbusController::onDeviceConnected()
{
    ModbusService *modbusService = qobject_cast<ModbusService *>(sender());
    if (!modbusService)
        return;

    QString deviceId = modbusService->currentDeviceId();
    qInfo() << "ModbusController: 设备连接成功信号 -" << deviceId;

    if (deviceId.isEmpty())
    {
        deviceId = m_currentDeviceId;
    }

    // 更新当前设备信息
    if (!deviceId.isEmpty())
    {
        if (m_deviceModel)
        {
            m_deviceModel->updateDeviceStatus(deviceId, "online");
        }

        if (m_currentDeviceId != deviceId)
        {
            switchToDevice(deviceId);
        }
    }

    // 更新状态
    if (m_currentDeviceId == deviceId)
    {
        m_isConnected = true;
        updateConnectionStatus(QString("已连接: %1").arg(deviceId));
        emit isConnectedChanged();
    }

    // 记录日志与对外事件
    if (!deviceId.isEmpty())
    {
        Logger::instance()->logOperation("connect_device", deviceId, "连接设备成功");
        emit deviceConnected(deviceId);

        // 自动启动数据采集（1秒间隔）
        startDataCollection(deviceId, 1000);
    }
}

// ModbusService 断开连接
void ModbusController::onDeviceDisconnected()
{
    ModbusService *modbusService = qobject_cast<ModbusService *>(sender());
    if (!modbusService)
        return;

    QString deviceId = modbusService->currentDeviceId();
    qInfo() << "ModbusController: 设备断开连接信号 -" << deviceId;

    if (!deviceId.isEmpty() && m_deviceModel)
    {
        m_deviceModel->updateDeviceStatus(deviceId, "offline");
        Logger::instance()->logOperation("disconnect_device", deviceId, "设备连接断开");
    }

    // 更新状态
    if (m_currentDeviceId == deviceId)
    {
        m_isConnected = false;
        updateConnectionStatus("已断开");
        emit isConnectedChanged();
    }

    // 停止数据采集
    if (!deviceId.isEmpty())
    {
        stopDataCollection(deviceId);
        emit deviceDisconnected(deviceId);
    }
}

// ModbusService 连接错误
void ModbusController::onDeviceConnectionError(const QString &error)
{
    ModbusService *modbusService = qobject_cast<ModbusService *>(sender());
    if (!modbusService)
        return;

    QString deviceId = modbusService->currentDeviceId();
    qWarning() << "ModbusController: 设备连接错误 -" << deviceId << "-" << error;

    updateConnectionStatus(QString("连接错误: %1").arg(error));
    if (!deviceId.isEmpty() && m_deviceModel)
    {
        m_deviceModel->updateDeviceStatus(deviceId, "error");
    }
    emit deviceConnectionFailed(deviceId, error);
}

// 数据采集完成
void ModbusController::onDataCollected(const DataPoint &dataPoint)
{
    // 添加到实时数据模型
    if (m_dataRecordModel)
    {
        m_dataRecordModel->addDataPoint(dataPoint);
    }

    emit newDataReceived(dataPoint.deviceId());
}

// 采集成功
void ModbusController::onCollectionSuccess(const QString &deviceId)
{
    qDebug() << "ModbusController: 数据采集成功 -" << deviceId;
}

// 采集失败
void ModbusController::onCollectionFailed(const QString &deviceId, const QString &error)
{
    qWarning() << "ModbusController: 数据采集失败 -" << deviceId << "-" << error;
    emit dataCollectionFailed(deviceId, error);
}

// 创建 ModbusService
ModbusService *ModbusController::createModbusService(const QString &deviceId)
{
    // 如果已存在，直接返回
    if (m_modbusServices.contains(deviceId))
    {
        return m_modbusServices[deviceId];
    }

    // 创建新的 ModbusService
    ModbusService *modbusService = new ModbusService(this);

    // 连接信号
    connect(modbusService, &ModbusService::connected,
            this, &ModbusController::onDeviceConnected);
    connect(modbusService, &ModbusService::disconnected,
            this, &ModbusController::onDeviceDisconnected);
    connect(modbusService, &ModbusService::connectionError,
            this, &ModbusController::onDeviceConnectionError);

    m_modbusServices[deviceId] = modbusService;

    qDebug() << "ModbusController: 创建 ModbusService -" << deviceId;
    return modbusService;
}

// 创建 DataCollector
DataCollector *ModbusController::createDataCollector(const QString &deviceId)
{
    // 如果已存在，直接返回
    if (m_dataCollectors.contains(deviceId))
    {
        return m_dataCollectors[deviceId];
    }

    // 创建新的 DataCollector
    DataCollector *collector = new DataCollector(this);

    // 连接信号
    connect(collector, &DataCollector::dataCollected,
            this, &ModbusController::onDataCollected);
    connect(collector, &DataCollector::collectionSuccess,
            this, &ModbusController::onCollectionSuccess);
    connect(collector, &DataCollector::collectionFailed,
            this, &ModbusController::onCollectionFailed);

    m_dataCollectors[deviceId] = collector;

    qDebug() << "ModbusController: 创建 DataCollector -" << deviceId;
    return collector;
}

// 获取 ModbusService
ModbusService *ModbusController::getModbusService(const QString &deviceId) const
{
    return m_modbusServices.value(deviceId, nullptr);
}

// 获取 DataCollector
DataCollector *ModbusController::getDataCollector(const QString &deviceId) const
{
    return m_dataCollectors.value(deviceId, nullptr);
}

// 清理设备资源
void ModbusController::cleanupDevice(const QString &deviceId)
{
    // 删除 ModbusService
    if (m_modbusServices.contains(deviceId))
    {
        ModbusService *service = m_modbusServices.take(deviceId);
        service->deleteLater();
    }

    // 删除 DataCollector
    if (m_dataCollectors.contains(deviceId))
    {
        DataCollector *collector = m_dataCollectors.take(deviceId);
        collector->deleteLater();
    }

    qDebug() << "ModbusController: 清理设备资源 -" << deviceId;
}

// 更新连接状态
void ModbusController::updateConnectionStatus(const QString &status)
{
    if (m_connectionStatus == status)
        return;

    m_connectionStatus = status;
    emit connectionStatusChanged();
}
